package com.mawc.equipower.utils;

public class HexUtil {
    /**
     * @param: [hex]
     * @return: int
     * @description: 按位计算，位值乘权重
     */
    private  static int  hexToDecimal(String hex){
        int outcome = 0;
        for(int i = 0; i < hex.length(); i++){
            char hexChar = hex.charAt(i);
            outcome = outcome * 16 + charToDecimal(hexChar);
        }
        return outcome;
    }
    /**
     * @param: [c]
     * @return: int
     * @description:将字符转化为数字
     */
    private  static int charToDecimal(char c){
        if(c >= 'A' && c <= 'F'){
            return 10 + c - 'A';
        }
        else{
            return c - '0';
        }
    }
    public static Integer hexToInt(String content){
        content = content.toUpperCase();
        return hexToDecimal(content);
    }

    /**
     * 字节数组转16进制
     * @param bytes 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }
}
